package com.bridgetree.jubaocrm.ui.project;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.JsonObjectPostRequest;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.ui.ProgressDialogUtil;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.Projects;
import com.bridgetree.jubaocrm.ui.LoginUtil;
/**
 *添加外出申请
 */
public class XMChildAddEgressActivity extends Activity {
	private final String TAG ="XMChildAddEgressActivity";
	private Projects mProjects ;
	private Button xm_egress_bt_selecttime;
	private Context mContext;
	private RelativeLayout xm_addegress_RelativeLayout;
	private LinearLayout xm_egress_LinearLayout_jinr;
	private TextView xm_egress_ed_leixing;
	private EditText xm_egress_ed_jinr;
	private InputMethodManager mInputMethodManager ;
	private Button xm_egress_ed_khlxr;
	private String user_id =""; 
	private String token ="";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.xmaddegress);
		mContext = this;

		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}
		mInputMethodManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");
		
		TextView xm_egress_tv_title =(TextView)findViewById(R.id.xm_egress_tv_title);
		 xm_egress_ed_leixing =(TextView)findViewById(R.id.xm_egress_ed_leixing);
		 xm_egress_ed_jinr =(EditText)findViewById(R.id.xm_egress_ed_jinr);
	    xm_addegress_RelativeLayout =(RelativeLayout)findViewById(R.id.xm_addegress_RelativeLayout);
	    xm_egress_LinearLayout_jinr =(LinearLayout)findViewById(R.id.xm_egress_LinearLayout_jinr);
		if(intent.getExtras()!=null){
			mProjects = (Projects)intent.getExtras().getSerializable("my_projects");
			xm_egress_tv_title.setText("外出申请/交流记录");
		}

		findViewById(R.id.xm_egress_RelativeLayout_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		findViewById(R.id.xm_egress_ed_leixing).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				xm_addegress_RelativeLayout.setVisibility(View.VISIBLE);
			}
		});
		
		findViewById(R.id.xm_egress_bt_ok).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				getAddEgress();
			}
		});

		xm_egress_bt_selecttime =(Button)findViewById(R.id.xm_egress_bt_selecttime);
		xm_egress_bt_selecttime.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				selectDate();
			}
		});
		
		xm_egress_LinearLayout_jinr.setVisibility(View.GONE);
		
		TextView miantan =(TextView)findViewById(R.id.miantan);
		TextView nomiantan =(TextView)findViewById(R.id.nomiantan);
		TextView quxiao =(TextView)findViewById(R.id.quxiao);
		miantan.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				xm_egress_ed_leixing.setText("面谈");
				xm_addegress_RelativeLayout.setVisibility(View.GONE);
				xm_egress_LinearLayout_jinr.setVisibility(View.GONE);
			}
		});
		nomiantan.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				xm_egress_ed_leixing.setText("非面谈");
				xm_addegress_RelativeLayout.setVisibility(View.GONE);
				xm_egress_LinearLayout_jinr.setVisibility(View.VISIBLE);
			}
		});
		quxiao.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				xm_addegress_RelativeLayout.setVisibility(View.GONE);
			}
		});
		
		xm_egress_ed_khlxr = (Button) findViewById(R.id.xm_egress_ed_khlxr);
		xm_egress_ed_khlxr.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(mContext, XMChildCustomerContactActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("fangtan", "select");
				bundle.putSerializable("my_projects", mProjects);
				bundle.putSerializable("cons", xm_egress_ed_khlxr.getText().toString());
				intent.putExtras(bundle);
				startActivityForResult(intent, 0);
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode==XMChildCustomerContactActivity.Finish_Select){
			String cons =data.getStringExtra("cons");
			xm_egress_ed_khlxr.setText(cons);
		}
	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (getCurrentFocus() != null
					&& getCurrentFocus().getWindowToken() != null) {
				mInputMethodManager.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
		return super.onTouchEvent(event);
	}

	String date="";
	String time="";
	Dialog Datedialog = null;
	Dialog Timedialog = null;
	private void selectDate() {
		Calendar calendar = Calendar.getInstance();
		DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker datePicker, int year, int month,
					int dayOfMonth) {
				date =year+"-"+(month+1)+"-"+dayOfMonth;
				Timedialog.show();
			}
		};
		Datedialog = new DatePickerDialog(this, dateListener,
				calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH));
		Datedialog.show();
		
		TimePickerDialog.OnTimeSetListener timeListener = 
			new TimePickerDialog.OnTimeSetListener() {

			@Override
			public void onTimeSet(TimePicker timerPicker,
					int hourOfDay, int minute) {
				time =" "+hourOfDay+":"+minute;
				xm_egress_bt_selecttime.setText(date+time);
			}
		};
		Timedialog = new TimePickerDialog(this, timeListener,
				calendar.get(Calendar.HOUR_OF_DAY),
				calendar.get(Calendar.MINUTE),
				false); //是否为二十四制
	}


	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title)
		.setMessage(content).setPositiveButton("确定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (content != null && content.trim().equals("用户不存在")) {
					// finish();
				}
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}

			}
		}).show();
	}

	@SuppressLint("SimpleDateFormat")
	private void getAddEgress() {
		TextView xm_egress_ed_leixing = (TextView) findViewById(R.id.xm_egress_ed_leixing);
		EditText xm_egress_ed_address = (EditText) findViewById(R.id.xm_egress_ed_address);
		EditText xm_egress_ed_mycyr = (EditText) findViewById(R.id.xm_egress_ed_mycyr);
		String selecttime ="";
		if(xm_egress_bt_selecttime.getText().equals("选取日期")){
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
			selecttime = sdf.format( new  Date());
		}else{
			selecttime = xm_egress_bt_selecttime.getText().toString();
		}
		
		String address =xm_egress_ed_address.getText().toString();
		String people_of_us =xm_egress_ed_mycyr.getText().toString();
		String people_of_client =xm_egress_ed_khlxr.getText().toString();
		String tmp ="";
		if(address.equals("")|| address.length()<2 || address.length()>50){
			tmp+="地点必须是2-50个字符\n";
		}
		if(people_of_client.length()<2){
			tmp+="客户联系人长度必须大于1个字符\n";
		}
		if(people_of_us.length()<2 || people_of_us.length()>50){
			tmp+="我方参与者必须是2-50个字符\n";
		}
		if(people_of_client.length()>50){
			tmp+="选择了过多的客户联系人\n";
		}
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else if (!tmp.equals("")) {
			openDailog("失败提示", tmp);
		} else{
			final ProgressDialog progressDialog=ProgressDialogUtil.show(mContext);
			
			HashMap<String, String> mMap = new HashMap<String, String>();
			mMap.put("project_id",  mProjects.getProject_id());
			mMap.put("user_id",user_id);
			mMap.put("token", token);
			mMap.put("validation", CRMUserBaseInfo.kValication);
			mMap.put("client_id", mProjects.getClient_id());
			mMap.put("time_line", selecttime);
			mMap.put("address", address);
			mMap.put("people_of_client", people_of_client);
			mMap.put("people_of_us", people_of_us);
			mMap.put("content", xm_egress_ed_jinr.getText().toString());
			mMap.put("interview_type", xm_egress_ed_leixing.getText().toString());
			mMap.put("interview_id","");
			String URL = Network.API_DOMAIN+"/interview";

			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectPostRequest jsonObjectPostRequest = new JsonObjectPostRequest(
					URL, new Response.Listener<JSONObject>() {

						@Override
						public void onResponse(JSONObject response) {
							ProgressDialogUtil.dissmis(progressDialog);
							try {
								Log.e("wop"," response  = "+response);
								if (!response.isNull("errors")) {
									String errors = response.get("errors").toString();
									if (errors.equals("[]")) {
										finish();
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr.length(); i++) {
													JSONObject jsonObj2 = jsonArr.getJSONObject(i);
													if (!jsonObj2.isNull("desc")) {
														String desc = jsonObj2.getString("desc");
														String msg;
														if(isInteger(desc)){
															char ss = (char)Integer.parseInt(desc, 16);
															msg=String.valueOf(ss);
														}else{
															msg=desc;
														}
														openDailog("失败提示", String.valueOf(msg));
														mLoginError.setDesc(desc);
													}
													if (!jsonObj2.isNull("value")) {
														String value = jsonObj2.getString("value");
														mLoginError.setValue(value);
													}
												}
											}
										}
									}
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							ProgressDialogUtil.dissmis(progressDialog);
							Toast.makeText(mContext, "网络未连接！",
									Toast.LENGTH_LONG).show();
						}
					}, mMap);
			requestQueue.add(jsonObjectPostRequest);
		}

	}
	public static boolean isInteger(String value) {  
	     try {  
	         Integer.parseInt(value);  
	         return true;  
	     } catch (NumberFormatException e) {  
	         return false;  
	     }  
	 }  


}
